<template>
  <div style="height: 100%;width: 100%; overflow: hidden">
    <editor
        v-model="myValue"
        :init="init"
        :enabled="enabled"
        :id="tinymceId"
    ></editor>
  </div>
</template>

<script setup>
import {computed, reactive, watch, ref, nextTick, onMounted} from "vue";
import axios from "axios";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/icons/default/icons";
import "tinymce/models/dom";
import "tinymce/themes/silver";
import "tinymce/plugins/image";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/preview";
import "tinymce/plugins/emoticons";
import "tinymce/plugins/emoticons/js/emojis.js";
import "tinymce/plugins/code";
import "tinymce/plugins/link";
import "tinymce/plugins/advlist";
import "tinymce/plugins/codesample";
import "tinymce/plugins/autoresize";
import "tinymce/plugins/quickbars";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/autolink";
import "tinymce/plugins/directionality";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/charmap";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/importcss";
import "tinymce/plugins/accordion";
import "tinymce/plugins/anchor";
import "tinymce/plugins/fullscreen";
import debug from "@/utils/env";

const emits = defineEmits(["update:modelValue", "setHtml"]);
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  baseUrl: {
    type: String,
    default: "",
  },
  enabled: {
    type: Boolean,
    default: true,
  },
  editable_root: {
    type: Boolean,
    default: true,
  },
  plugins: {
    type: [String, Array],
    default:
        "importcss autoresize searchreplace autolink directionality code visualblocks visualchars fullscreen image link codesample table charmap nonbreaking anchor insertdatetime advlist lists wordcount charmap quickbars emoticons accordion",
  },
  knwlgId: {
    type: String,
  },
  toolbar: {
    type: [String, Array, Boolean],
    default: "undo redo | accordion accordionremove | blocks fontfamily fontsize| bold italic underline strikethrough ltr rtl  | align numlist bullist | link image | table | lineheight outdent indent| forecolor backcolor removeformat | charmap emoticons | anchor codesample",
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  minHeight: {
    type: Number,
    default: 630,
  },
});

const loading = ref(false);
const tinymceId = ref(
    "vue-tinymce-" + +new Date() + ((Math.random() * 1000).toFixed(0) + "")
);

const init = reactive({
  selector: "#" + tinymceId.value,
  license_key: 'gpl',
  language_url: "/saas-service/tinymce/langs/zh_CN.js",
  language: "zh_CN",
  skin_url: "/saas-service/tinymce/skins/ui/oxide",
  editable_root: props.editable_root,
  height: 600,
  branding: false,
  promotion: false,
  menubar: "edit view insert format tools table",
  paste_data_images: true,
  image_dimensions: false,
  plugins: props.plugins,
  toolbar: props.toolbar,
  convert_urls: false,
  link_default_target: "_blank",
  link_context_toolbar: true,
  quickbars_insert_toolbar: "image codesample table",
  quickbars_image_toolbar: "alignleft aligncenter alignright | rotateleft rotateright | imageoptions",
  editimage_toolbar: "rotateleft rotateright | flipv fliph | editimage imageoptions",
  font_family_formats:
      "Arial=arial,helvetica,sans-serif; 宋体=SimSun; 微软雅黑=Microsoft Yahei; Impact=impact,chicago;",
  font_size_formats: "11px 12px 14px 16px 18px 24px 36px 48px 64px 72px",
  image_caption: true,
  editimage_cors_hosts: ["picsum.photos"],
  noneditable_class: "mceNonEditable",
  toolbar_mode: "wrap",
  content_style:
      "body { font-family:Helvetica,Arial,sans-serif; font-size:16px }p {margin:3px; line-height:24px;}",
  image_advtab: true,
  importcss_append: true,
  paste_webkit_styles: "all",
  paste_merge_formats: true,
  nonbreaking_force_tab: false,
  paste_auto_cleanup_on_paste: false,
  file_picker_types: "file",
  images_upload_handler: function (blobInfo, progress) {
    new Promise((resolve, reject) => {
      let file = blobInfo.blob();
      if (file.size / 1024 / 1024 > 200) {
        reject({
          message: "上传失败，图片大小请控制在 200M 以内",
          remove: true,
        });
      }
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", 1);
      axios.post(import.meta.env.VITE_API_BASE_URL+"/system/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
          progress(
              Math.round((progressEvent.loaded / progressEvent.total) * 100)
          );
        },
      }).then((res) => {
        resolve(res.data.url);
      }).catch()
    });
  },
});

const myValue = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  },
});

watch(
    () => myValue.value,
    () => {
      emits(
          "setHtml",
          tinymce.activeEditor.getContent({format: "text"}),
          myValue.value
      );
    }
);

watch(
    () => props.readonly,
    (newValue, oldValue) => {
      nextTick(() => {
        tinymce.activeEditor.mode.set(newValue ? "readonly" : "design");
        let iframeDom = document.querySelector("iframe");
        iframeDom &&
        (iframeDom.contentWindow.document.body.style.margin = newValue
            ? 0
            : "16px");
      });
    },
    {immediate: true}
);

onMounted(() => {
  tinymce.init({});
});

const handleSetContent = (content) => {
  tinymce.activeEditor.setContent(content);
};

const handleGetContent = () => {
  return tinymce.activeEditor.getContent();
};

defineExpose({
  handleSetContent,
  handleGetContent,
});
</script>

<style lang="less" scoped>
:deep(.tox-tinymce) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  .tox-statusbar {
    display: none;
  }
}
</style>